//
//  SearchViewController.m
//  carcar
//
//  Created by dlios on 15/9/22.
//  Copyright (c) 2015年 DIOS. All rights reserved.
//

#import "SearchViewController.h"
#import "BaseHeader.h"

#import "SearchWebViewController.h"

@interface SearchViewController ()<UITableViewDataSource , UITableViewDelegate,UISearchBarDelegate>

{
    UISearchBar *_searchBar;
    NSMutableArray *_infoArray;
    NSMutableArray *_searchinfoArray;
    
    UITableView *_tableView;
    NSInteger _page;
    UIButton *_button;
}
@property (nonatomic , retain) NSMutableArray * listDic ;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self.view setBackgroundColor:[UIColor whiteColor]];
    // Do any additional setup after loading the view.
    _infoArray = [[NSMutableArray alloc] init];
    _searchinfoArray = [[NSMutableArray alloc] init];
 
    
    self.hiddenView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, mainScreen_Width, 64)];
    [self.view addSubview:self.hiddenView];
    [self.hiddenView setBackgroundColor:[UIColor colorWithWhite:0.901 alpha:1.000]];
    self.hiddenView.alpha = .5;
    
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setFrame:CGRectMake(10, 15, 60, 30)];
    [_button setTitle:@"返回" forState:UIControlStateNormal];
    [_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.hiddenView addSubview:_button];
    [self creatSeachBar];
   
}
- (void)back
{
    [_searchBar resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 创建seachBar
- (void)creatSeachBar
{
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(70, 10, self.view.frame.size.width - 90, 45)];
    [_searchBar sizeToFit];
    _searchBar.showsCancelButton = NO;
    _searchBar.barStyle = UIBarStyleDefault;
   _searchBar.placeholder = @"搜索商品";
    _searchBar.delegate = self;
    _searchBar.searchBarStyle = UISearchBarStyleMinimal;
    [_searchBar becomeFirstResponder];
    _searchBar.showsCancelButton = YES;
    [self.hiddenView addSubview:_searchBar];
}
#pragma mark - 上拉刷新
- (void)readFoot
{
    __block SearchViewController *vc = self;
    [_tableView addLegendFooterWithRefreshingBlock:^{
        vc.number ++;
        [vc AFDate:vc.number searchstr:vc.seachStr];
    }];
}
- (void)AFDate:(NSInteger)number searchstr:(NSString *)searStr
{
    
    NSString *str = [searStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [AFNblock getdataWithString:[NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.8.8/sou/video.ashx?pm=2&q=%@&p=%ld&s=20",str,number] block:^(id block) {
        
        NSArray *arry = [[NSMutableArray alloc]init];
        arry = [[block objectForKey:@"result"]objectForKey:@"list"];
        if (arry.count == 0) {
            
            [_tableView removeFromSuperview];
            [_lable removeFromSuperview];
            _lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, mainScreen_Width, 160 * suitableScreen_Height)];
            _lable.center = self.view.center;
            [_lable setTextAlignment:NSTextAlignmentCenter];
            [_lable setFont:[UIFont systemFontOfSize:20]];
            _lable.text = @"没有搜索到相关🚗";
            [self.view addSubview:_lable];
            
        }else
        {
            NSMutableDictionary * reDic = [block objectForKey:@"result"];
            _listDic = [reDic objectForKey:@"list"];
            for (NSMutableDictionary * dic in _listDic) {
                _seachModle = [SeachModel modelWithDictionary:dic];
                
                _seachModle.titleheight = [TQStringWithHight HeightWithText:_seachModle.title width:255 * suitableScreen_Width font:[UIFont systemFontOfSize:15]];
                [_infoArray addObject:_seachModle];
                
            }
             [self readFoot];
            [_tableView reloadData];
            [_tableView.footer endRefreshing];
        }
        
    }];

}

#pragma mark - searchBar delagete
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
     //点击第一步 把上次创建的tableview 删除
    [_tableView removeFromSuperview];
     //第二步  再次创建tableview
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 * suitableScreen_Width,mainScreen_Width, mainScree_Height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
   
     //第三步  把上次的数组拿掉
    [_infoArray removeAllObjects];
    [_tableView reloadData];
    [_searchBar resignFirstResponder];
    self.seachStr= searchBar.text;
    ///第四步  请求数据
   
    [self AFDate:1 searchstr:self.seachStr];
    
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
   
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    for (UIView *view in [[_searchBar.subviews lastObject]subviews]) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *cancelButton = (UIButton *)view;
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
}
#pragma mark - tableView delegate&dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _infoArray.count ;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"cellId";
    SeachViewTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[SeachViewTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    _seachModle = [_infoArray objectAtIndex:indexPath.row];
    [cell setDate:_seachModle seach:self.seachStr];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 80 * suitableScreen_Width ;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchWebViewController * sear = [[SearchWebViewController alloc]init];
    SeachModel *model = [_infoArray objectAtIndex:indexPath.row];
    sear.cid = model.id;
    [self presentViewController:sear animated:YES completion:^{
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
